package servlet;

import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/SearchServlet.do")
public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String searchUsername = request.getParameter("username");
        String idString = request.getParameter("id");
        List<Map<String, Object>> searchResults = null;

        if (searchUsername != null && !searchUsername.isEmpty()) {
            searchResults = performSearch("SELECT * FROM user WHERE username LIKE ?", "%" + searchUsername + "%");
        } else if (idString != null && !idString.isEmpty()) {
            try {
                int id = Integer.parseInt(idString);
                searchResults = performSearch("SELECT * FROM user WHERE user_id = ?", id);
            } catch (NumberFormatException e) {
                // Handle the error if id is not a valid integer
                request.setAttribute("error", "Invalid ID format");
                request.getRequestDispatcher("home/404.html").forward(request, response);
                return;
            }
        }

        HttpSession session = request.getSession();
        session.setAttribute("searchResults", searchResults);

        response.sendRedirect(request.getContextPath() + "/background1/admin/usermanager.jsp");
    }

    private List<Map<String, Object>> performSearch(String sql, Object parameter) {
        List<Map<String, Object>> userList = new ArrayList<>();
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet resultSet = null;

        try {
            resultSet = jdbcUtil.prepareQuery(sql, parameter);

            while (resultSet != null && resultSet.next()) {
                Map<String, Object> user = new HashMap<>();
                user.put("id", resultSet.getInt("user_id"));
                user.put("username", resultSet.getString("username"));
                user.put("email", resultSet.getString("email"));
                user.put("phone", resultSet.getString("phone"));
                user.put("created_at", resultSet.getString("created_at"));
                user.put("user_type", resultSet.getInt("user_type"));
                userList.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                jdbcUtil.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return userList;
    }
}
